<?php session_start();
include("../../Connections/connect_admin.php");
if($_POST['task']=="add")
{
	$id=$_POST["roleid"];
	$name=$_POST["rolename"];
	$desc=$_POST["desc"];
	$query="INSERT INTO role(RoleID,RoleName,Description) VALUES('$id','$name','$desc')";
	
	if(mysql_query($query))
	{
		
		header('location:../Role.php?e=0');
		
	}
	else
	{
		header('location:../Role.php?e=1');
		
	}
}

else if($_POST['task']=="delete")
{
	$id=$_POST["roleid"];
	$user=$_SESSION['username'];
	$query="UPDATE role SET IsDeleted = 1,DeletedDate = Now(),DeletedUser = '$user' WHERE RoleID = '$id'";
	if(mysql_query($query))
	{
		$response=array(
						'ok'=>true,
						'msg'=>'Xóa quyền Thành Công'
						);
		echo json_encode($response);
	}
	else
	{
		$response=array(
						'ok'=>false,
						'msg'=>'Xóa quyền Thất Bại'
						);
		echo json_encode($response);
	}
}
else if($_POST['task']=="update")
{
	$id=$_POST["roleid"];
	$name=$_POST["rolename"];
	$desc=$_POST["desc"];
	$query="UPDATE role SET RoleName = '$name',Description = '$desc' WHERE RoleID='$id'";
	
	if(mysql_query($query))
	{
		
		header('location:../Role.php?e=2');
		
	}
	else
	{
		header('location:../Role.php?e=3');
		
	}

}
else if($_POST['task']=="checkExist")
{
	
$id=trim($_POST["roleid"]);
$query="SELECT * FROM `role` u WHERE u.RoleID='$id'";
$result=mysql_query($query);
$response=array();
if(mysql_num_rows($result)>0)
{
	 $response = array(
        'ok' => true, 
        'msg' => "RoleID is existed ");
}
else
{
	 $response = array(
        'ok' => false, 
        'msg' => "RoleID can use ");
}
echo json_encode($response);

}

else if($_POST['task']='searchgroup')
{
	$groupid=intval($_POST['groupid']);
	$keyword=$_POST['keyword'];
	$query="SELECT r.RoleID, r.RoleName FROM `role` r WHERE r.IsDeleted=0 AND (r.RoleID LIKE '%$keyword%' OR r.RoleName LIKE '%$keyword%') AND r.RoleID NOT IN (SELECT g.RoleID FROM grouproledetail g INNER JOIN `role` r ON r.RoleID = g.RoleID WHERE g.GroupRoleID=$groupid) ";
	$result=mysql_query($query);
	$roles=array();
	$i=0;
	while($row=mysql_fetch_assoc($result))
	{
		$roles[$i]=array('roleid'=>$row['RoleID'],'rolename'=>$row['RoleName']);
		$i++;		
	}
	echo json_encode($roles);
}
?>